<?php
define('codeark.google-analytics-generator', '');

interface IGoogleAnalyticsVariable {
	public function getName();
	public function getValue();
	public function getOptScope();
}

class GoogleAnalyticsGenerator {

	private $variables;
	private $trackerId;
	private $debug;
	
	function __construct($trackerId) {
		$this->variables = array();
		$this->trackerId = $trackerId;
	}

	function addVariable($googleAnalyticsVariable){
	
		if (sizeof($this->variables) == 5) {
			trigger_error('no more variable slots are available (5/5)');
			return false;
		}
		
		$this->variables[$googleAnalyticsVariable->getName()] = $googleAnalyticsVariable;
		
		return sizeof($this->variables);
	}

	function removeVariable($googleAnalyticsVariable) {
		unset($this->variables[$googleAnalyticsVariable->getName()]);
	}
	
	function setDebugModeActive($debug) {
		$this->debug = $debug;	
	}
	
	function generateVariablesScriptTag() {
		
		$code = array('<script type="text/javascript">');
		
		$code[] = " try { ";
				
		$code[] = '_gaq.push(';
		
		$varcode = array();

		$slotIndex = 1;

		// google only allows 64 byte length for name and value combined. Moreover, value length is counted
		// after encodeURIComponent is applied
		foreach($this->variables as $v) {
			$name = $v->getName();
			$len = 64 - strlen($name);
			
			if ($len < 2) {
				trigger_error("The variable's name: $name is too long and will be omitted");
				continue;
			}
			
			$value=	$v->getValue();
			
			$len = $len - strlen(jsEncodeURIComponent($value));
			
			if ($len < 0) {
				trigger_error("The variable $name name and encoded value length exceeds the allotted 64 byte length and will be omitted");
				continue;
			}
			
			$varcode[] = "['_setCustomVar', $slotIndex, '$name', '$value', {$v->getOptScope()}]";
			$slotIndex++;
		}

		$code[] = implode(',', $varcode);
		$code[] = '); } catch (e) {';
		
		if (!$this->debug) $code[] = "alert(e);";
		
		$code[] = '} </script>';

		return implode('', $code);
	}

	function generateSetupScriptTag() {
		$code = <<<CODE
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '{$this->trackerId}']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
CODE;
		return $code;	
	}

}

/**
 * 
 * Simulates Javascript encodeURIComponent. 
 * 
 * Based on comparison table found in this url:
 * 
 * http://devpro.it/examples/php_js_escaping.php
 * 
 * @param unknown_type $string
 */
function jsEncodeURIComponent($string) {
	$string = urlencode($string);
	$string = str_replace('+', '%20', $string);
	$string = str_replace('%21', '!', $string);
	$string = str_replace('%27', "'", $string);
	$string = str_replace('%28', '(', $string);
	$string = str_replace('%29', ')', $string);
	$string = str_replace('%2A', '*', $string);
	$string = str_replace('%7E', '~', $string);	
	
	return $string;
}

/**
 * see jsEncodeURIComponent
 *
 * @param unknown_type $string
 */
function jsDecodeURIComponent($string) {
	
	$string = str_replace('%20', '+', $string);
	$string = str_replace('!', '%21', $string);
	$string = str_replace("'", "%27", $string);
	$string = str_replace('(', '%28', $string);
	$string = str_replace(')', '%29', $string);
	$string = str_replace('*', '%2A', $string);
	$string = str_replace('~', '%7E', $string);
	
	$string = urldecode($string);
	
	return $result;
}

?>